package com.rk.app.poll.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratedStackPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 */
public class PollViewWidget extends Composite {
	private DecoratedStackPanel stackPanel = new DecoratedStackPanel();

	private FlexTable pollFlexTable = new FlexTable();

	private TextArea commentTextBox = new TextArea();

	private RadioButton choices[] = null;

	private Button submitButton = new Button("Submit");

	private final PollServiceAsync pollingService = GWT.create(PollService.class);

	private Poll poll = null;

	/**
	 * Entry point method.
	 */
	public PollViewWidget(Poll poll) {
		if (poll == null) {
			Window.alert("Poll does not exists.");
			// Window.Location.replace(Window.Location.getProtocol() + "/pollApp.html");
		} else if (!poll.isOpen()) {
			Window.alert("The poll is closed, you can't vote.");
			// Window.Location.replace(Window.Location.getProtocol() + "/pollApp.html");
		} else {
			this.poll = poll;
			String uri = Window.Location.getPath();
			pollingService.getSignInURL(uri, new AsyncCallback<String>() {

				public void onFailure(Throwable caught) {
					Window.alert("Error Occured:-\n" + caught.getLocalizedMessage());
				}

				public void onSuccess(String result) {
					if (result != null && result.toLowerCase().indexOf("sign out") >= 0) {
						initPollUI();
					} else {
						Window.alert("Please sign in to submit your vote.");
						Window.Location.replace(Window.Location.getProtocol() + "/pollApp.html");
					}
				}

			});
		}
		initWidget(stackPanel);
	}

	/**
	 * Add stock to FlexTable. Executed when the user clicks the addStockButton or presses enter in the
	 * newSymbolTextBox.
	 */
	private void submitPoll() {
		PollResponse pollResponse = new PollResponse();
		pollResponse.setPollId(poll.getId());
		pollResponse.setComments(commentTextBox.getText());
		for (int i = 0; i < choices.length; i++) {
			if (choices[i].getValue()) {
				pollResponse.setSelectedChoice(choices[i].getText());
			}
		}
		// pollResponse.setTime(SimpleDateFormat.getTimeInstance().format(Calendar.getInstance().getTime().toString()));
		pollingService.savePollResponse(pollResponse, new AsyncCallback<String>() {
			public void onFailure(Throwable caught) {
				Window.alert(caught.getLocalizedMessage());
			}

			public void onSuccess(String result) {
				if (result.equals("save")) {
					Window.alert("Thank you for participating. Your choice is saved.");
				} else if (result.equals("update")) {
					Window.alert("Thank you for participating. Your choice is updated");
				} else {
					Window.alert("Sorry, due to unkown error operation failed.");
				}
				commentTextBox.setText("");

				Window.Location.replace(Window.Location.getProtocol() + "/pollApp.html");
			}
		});
	}

	

	private void initPollUI() {
		int row = 0;

		stackPanel.setWidth("100%");
		String header = PollMain.getPollHeader(poll);
		choices = new RadioButton[poll.getChoices().length];
		for (int i = 0; i < choices.length; i++) {
			choices[i] = new RadioButton("Choice", poll.getChoices()[i]);
			pollFlexTable.setWidget(row++, 0, choices[i]);
		}
		pollFlexTable.setWidget(row++, 0, commentTextBox);
		pollFlexTable.setStyleName("formPanel");
		commentTextBox.setTitle("Add your comments here");
		submitButton.setEnabled(false);

		HorizontalPanel commandPanel = new HorizontalPanel();
		commandPanel.add(submitButton);
		commandPanel.setStyleName("formCommandPanel");

		VerticalPanel vPanel = new VerticalPanel();
		vPanel.setWidth("100%");
		pollFlexTable.setWidth("100%");
		commandPanel.setWidth("100%");
		vPanel.add(pollFlexTable);
		vPanel.add(commandPanel);

		stackPanel.add(vPanel, header, true);
		commentTextBox.setFocus(true);

		FocusHandler focusHandler = new FocusHandler() {
			public void onFocus(FocusEvent event) {
				submitButton.setEnabled(true);
			}
		};
		for (int i = 0; i < choices.length; i++) {
			choices[i].addFocusHandler(focusHandler);
			choices[i].addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					submitButton.setEnabled(true);
				}
			});
		}

		// Listen for mouse events on the Add button.
		submitButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				submitPoll();
			}
		});

		// Listen for keyboard events in the input box.
		commentTextBox.addKeyPressHandler(new KeyPressHandler() {
			public void onKeyPress(KeyPressEvent event) {
				if (event.getCharCode() == KeyCodes.KEY_ENTER && submitButton.isEnabled()) {
					submitPoll();
				}
			}
		});
	}
}
